import React, { FC, useEffect, useState } from "react";
import { Pagination } from "antd";
import {
  LIST_PAGE_SIZE,
  LIST_PAGE_INDEX_KEY,
  LIST_PAGE_SIZE_KEY,
} from "../constant";
import {
  useSearchParams,
  useLocation,
  useNavigate,
  useParams,
} from "react-router-dom";

type PropsType = {
  total: number;
};

const ListPagination: FC<PropsType> = (props: PropsType) => {
  const { total } = props;
  const [size, setSize] = useState(LIST_PAGE_SIZE);
  const [index, setIndex] = useState(1);
  const [searchParams] = useSearchParams();
  const nav = useNavigate();
  const { pathname } = useParams();

  // 在URL中获取 分页相关数据： 当前页，当前页的展示条数
  useEffect(() => {
    let pag = parseInt(searchParams.get(LIST_PAGE_INDEX_KEY) || "") || 1;
    setIndex(pag);
    let current = parseInt(searchParams.get(LIST_PAGE_SIZE_KEY) || "") || 10;
    setSize(current);
  }, [searchParams]);

  // 分页跳转后，根据分页的设置更新路由
  function onChangePage(page: number, pageSize: number) {
    console.log(page, pageSize);
    searchParams.set(LIST_PAGE_INDEX_KEY, page.toString());
    searchParams.set(LIST_PAGE_SIZE_KEY, pageSize.toString());
    nav({
      pathname,
      search: searchParams.toString(), // a=1&b=2
    });
  }

  return (
    <div>
      <Pagination
        align="center"
        current={index}
        pageSize={size}
        total={total}
        onChange={onChangePage}
      />
    </div>
  );
};

export default ListPagination;
